<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryinfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
          </el-input>
        </el-col>
          <el-col :span="4">
        <el-button type="primary"  @click="dialogVisible = true">添加用户</el-button></el-col>
      </el-row>
    </el-card>
    <!-- 表格 -->
    <el-table border :data="userslist" stripe style="width: 100%">
      <el-table-column type="index" label="#"> </el-table-column>
      <el-table-column prop="username" label="姓名" width="170">
      </el-table-column>
      <el-table-column prop="email" label="email" width="170">
      </el-table-column>
      <el-table-column prop="mobile" label="电话" width="170">
      </el-table-column>
      <el-table-column prop="role_name" label="权限" width="170">
      </el-table-column>
      <el-table-column prop="mg_state" label="状态" width="170">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="showEdit(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" @click="removeuser(scope.row.id)"></el-button>
          <el-tooltip
            :enterable="false"
            effect="dark"
            content="分配角色"
            placement="top-start"
          >
            <el-button type="warning" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryinfo.pagenum"
      :page-sizes="[2, 3, 5, 10]"
      :page-size="queryinfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 增加弹框 -->
    <el-dialog
      @close="addDialogClosed"
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%">
      <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 当编辑 用户时，密码不显示 -->
        <el-form-item label="密码" prop="password" >
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="eidtlogVisible"
      width="30%"
      @close="closeEidt">
      <el-form :model="eidtForm" :rules="eidtrules" ref="eidtFormRef" label-width="100px">
        <el-form-item label="用户名" >
          <el-input v-model="eidtForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" >
          <el-input v-model="eidtForm.email" ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="eidtForm.mobile" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eidtlogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addEdit(id)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setrolesVisible"
      width="50%">
      <div>
        <p>当前的用户：{{ this.userinfo.username }}</p>
        <p>当前的角色：{{ this.userinfo.role_name }}</p>
        <p>分配的角色：
          <el-select v-model="Selectionroleid" placeholder="请选择">
            <el-option
              v-for="item in rolelist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setrolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="saverole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { userslist, userstate, addusers, addeidtusers, removeusers, getrolelist, setuserrole } from "@/api/index.js";

export default {
  data () {
    const checkEmail = (rule, value, callback) => {
      const regemail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (!regemail.test(value)) {
        return callback(new Error('请输入正确的邮箱格式'))
      }
      callback()
    }
    const checkMobile = (rule, value, callback) => {
      const regmobile = /^1[3-9][0-9]{9}$/;
      if (!regmobile.test(value)) {
        return callback(new Error('请输入正确的手机号'))
      }
      callback()
    }

    return {
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      userslist: [],
      total: 0,
      dialogVisible: false,
      eidtlogVisible: false,
      // 添加表单数据
      addForm: {
        username: "99979",
        password: "99999999",
        email: "1395607345@qq.com",
        mobile: "13013096767"
      },
      eidtForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 添加标点验证规则
      addFormrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]

      },
      eidtrules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      setrolesVisible: false,
      // 需要被分配角色的用户信息
      userinfo: {},
      rolelist: [],
      Selectionroleid: {}
    };
  },
  methods: {
    // 监听对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 加载用户列表数据
    async getuserlist () {
      const res = await userslist(this.queryinfo);

      try {
        this.userslist = res.data.users;
        this.total = res.data.total;
      } catch (error) {
        this.$message.error("获取用户列表失败");
      }
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newsize) {
      console.log(newsize);
      this.queryinfo.pagesize = newsize;
      this.getuserlist();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (page) {
      this.queryinfo.pagenum = page;
      this.getuserlist();
    },
    // 监听swith 开关状态改变的事件
    async userStateChange (row) {
      console.log(row);

      const res = await userstate({
        id: row.id,
        mg_state: row.mg_state
      });

      try {
        this.$message.success('修改用户状态成功')
        row.mg_state = !row.mg_state;
        this.getuserlist();
      } catch (error) {
        this.$message.error('修改用户状态失败')
      }
      console.log(res);
    },
    // 添加用户
    adduser () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        // const res = await addusers(this.addForm)
        // console.log(res);
        // this.$message.success('添加用户成功')
        // this.getuserlist()
        const res = await addusers(this.addForm)
        console.log(res, '232323');
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.getuserlist()
        this.dialogVisible = false

        // try {
        //   const res = await addusers(this.addForm)
        //   if (res.meta.status === 201) {
        //     this.$message.success('添加用户成功')
        //     this.getuserlist()
        //   }
        // } catch (error) {
        //   this.$message.error('111')
        // } finally {
        //   // this.dialogVisible = false
        // }
      })
    },
    // 修改时复制模版信息
    showEdit (row) {
      this.eidtlogVisible = true
      console.log(row);
      this.eidtForm = row
    },
    closeEidt () {
      // this.eidtlogVisible = false
      this.$refs.eidtFormRef.resetFields()
    },
    // 修改用户数据
    addEdit () {
      // console.log(id);
      this.$refs.eidtFormRef.validate(async (valid) => {
        if (!valid) return
        // const res = await addeidtusers(this.eidtForm)
        // console.log(res, '232323');
        // if(res.)

        const res = await addeidtusers(this.eidtForm)
        console.log(res, '232323');

        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        this.$message.success('更新用户信息成功')
        this.getuserlist()
        this.editDialogVisible = false
      })
    },
    // 弹框提示是否删除用户
    async removeuser (id) {
      const remove = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (remove !== 'confirm') {
        return this.$message.info('已取消删除')
      } else {
        const res = await removeusers(id)
        console.log(res, '2323wcewew2d23');

        if (res.meta.status !== 200) {
          return this.$message.error('删除用户失败')
        }
        this.$message.success('删除用户成功')
        this.getuserlist()
      }

      console.log(remove);
    },
    async setRole (userinfo) {
      console.log(userinfo, 'asdasdasdasdasda123213');
      this.userinfo = userinfo
      const res = await getrolelist();
      // console.log(res, 'asdasdasd ');
      try {
        this.rolelist = res.data;
        console.log(this.rolelist, 'asdasdasd ');
      } catch {
        this.$message.error('获取角色列表失败')
      }

      this.setrolesVisible = true;
    },
    // 点击按钮，分配角色
    async saverole () {
      console.log(this.userinfo.id);
      console.log(this.Selectionroleid, 'asdasdasd ');
      // const params = {
      //   a: 1,
      //   b: 2
      // }

      // if (!this.Selectionroleid) {
      //   return this.$message.error('角色没有变化');
      // }
      //   const res = await setuserrole(this.userinfo.id, this.selectroleid);
      //   console.log(res, '1');
      if (!this.Selectionroleid) {
        return this.$message.error('角色没有变化');
      }
      const res = await setuserrole(this.userinfo.id, this.Selectionroleid);
      console.log(res, '1');
    }
  },

  created () {
    this.getuserlist();
  }
};
</script>

<style>
.el-breadcrumb {
  margin-bottom: 20px;
  font-size: 12px;
}

.box-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-table {
  margin-top: 20px;
  font-size: 12px;
}

.el-pagination {
  /* text-align: center; */
  margin-top: 20px;
}
</style>
